package framework.mq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息发送者
 * @author JohnDeng
 * 2018年11月14日下午12:48:50 
 *
 */
public class QueueSender {
	// 默认连接用户名
		private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
		//	private static final String USERNAME ="admin";
		// 默认连接密码
	private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
//	private static final String PASSWORD = "admin";
		// 默认连接地址
	//	private static final String BROKER_URL = ActiveMQConnection.DEFAULT_BROKER_URL;
			private static final String BROKER_URL = "tcp://39.105.15.21:61616";
	
	public static void main(String[] args) {
		//1获取创建工场，创建实例
		ConnectionFactory  connectionFactory =new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKER_URL);
		try {
			Connection  connection=connectionFactory .createConnection();
			connection.start();
			//4.获取session(参数1：是否启动事务,参数2：消息确认模式)
			Session session=connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
	        Destination destination = session.createQueue("my-queue");
	        //创建生产者
	        MessageProducer producer = session.createProducer(destination);
	        for(int i=0; i<3; i++) {
	            TextMessage message = session.createTextMessage("message--"+i);
	            try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
	            //通过消息生产者发出消息
	            producer.send(message);
	        }
	        session.commit();
	        session.close();
	        connection.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
	
}
